package com.chinawayltd.ews.sample.manager.openApi.impl;

import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.openapi.OpenApiClient;
import com.chinawayltd.ews.openapi.Request;
import com.chinawayltd.ews.openapi.Response;
import com.chinawayltd.ews.sample.manager.openApi.CustomOpenApiManager;
import com.chinawayltd.ews.sample.manager.openApi.constant.OpenApiConstants;
import com.chinawayltd.ews.sample.model.openApi.TaskPushDTO;
import com.chinawayltd.ews.sample.model.openApi.VehicleHistoryDTO;

/**
 * @program: greeProject.timingTaskCenter
 * @description:
 * @author: xiazj
 * @create: 2018-05-02 15:31
 **/
@Service
public class CustomOpenApiManagerImpl extends BaseOpenApiManager implements CustomOpenApiManager {

    private static final String VERSION = "1.1";

	@Resource(name = "customOpenApiClient")
	private OpenApiClient customOpenApiClient;

	public void milkRunCall(String token, String data) throws Exception {
		String path = "/v1/algo-server/milk_run_call";

		if (StringUtils.isBlank(token)) {
			throw new NullPointerException("token must be not null!");
		}
		if (StringUtils.isBlank(data)) {
			throw new NullPointerException("data must be not null!");
		}

        JSONObject json = new JSONObject();
		json.put(OpenApiConstants.QUERY_PARAM_TOKEN, token);
		json.put(OpenApiConstants.QUERY_PARAM_DATA, data);
		json.put(OpenApiConstants.QUERY_PARAM_CUSTOM_VERSION, VERSION);
		// Body内容
		String body = json.toJSONString();

		Request request = this.getPostRequest(path, body);
		Response response = customOpenApiClient.execute(request);

		String responseBody = response.getBody();
		if (StringUtils.isNotBlank(responseBody)) {
			JSONObject responseResult = JSON.parseObject(responseBody);
			Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
			Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
			if (code != 0 || subCode != 0) {
				throw new RuntimeException("调用算法开始执行接口返回异常,返回结果【" + responseBody + "】");
			}
		}
	}

    public Float milkRunStatus(String token)throws Exception{
        Float result = null;
        String path = "/v1/algo-server/milk_run_status";

        if(StringUtils.isBlank(token)){
            throw new NullPointerException("token must be not null!");
        }
        JSONObject json = new JSONObject();
        json.put(OpenApiConstants.QUERY_PARAM_TOKEN, token);
        //Body内容
        String body = json.toJSONString();

        Request request = this.getPostRequest(path, body);
        Response response = customOpenApiClient.execute(request);

        String responseBody = response.getBody();
        if(StringUtils.isNotBlank(responseBody)){
            JSONObject responseResult = JSON.parseObject(responseBody);
            Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
            Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
            if(code == 0 && subCode == 0){
                String data = responseResult.getString(OpenApiConstants.RESULT_DATA);
                if(StringUtils.isNotBlank(data))
                    result = Float.parseFloat(data);
            }else{
                throw new RuntimeException("调用查询算法执行进度接口返回异常"+responseBody);
            }
        }
        return result;
    }

    public JSONObject milkRunFetch(String token) throws Exception {
        JSONObject result = null;
        //请求path
        String path = "/v1/algo-server/milk_run_fetch";

        if(StringUtils.isBlank(token)){
            throw new NullPointerException("token must be not null!");
        }
        JSONObject json = new JSONObject();
        json.put(OpenApiConstants.QUERY_PARAM_TOKEN, token);
        //Body内容
        String body = json.toJSONString();

        Request request = this.getPostRequest(path, body);
        Response response = customOpenApiClient.execute(request);

        String responseBody = response.getBody();
        if(StringUtils.isNotBlank(responseBody)){
            JSONObject responseResult = JSON.parseObject(responseBody);
            Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
            Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
            if(code == 0 && subCode == 0){
                String dataStr = responseResult.getString(OpenApiConstants.RESULT_DATA);
                JSONObject data = JSONObject.parseObject(dataStr);
                if(data != null && !data.isEmpty())
                    result = data;
            }else{
                throw new RuntimeException("调用获取算法结果接口返回异常"+responseBody);
            }
        }
        return result;
    }

    public void milkRunInterrupt(String token) throws Exception {

        String path = "/v1/algo-server/milk_run_interrupt";

        if (StringUtils.isBlank(token)) {
            throw new NullPointerException("token must be not null!");
        }
        JSONObject json = new JSONObject();
        json.put(OpenApiConstants.QUERY_PARAM_TOKEN, token);
        // Body内容
        String body = json.toJSONString();

        Request request = this.getPostRequest(path, body);
        Response response = customOpenApiClient.execute(request);

        String responseBody = response.getBody();
        if (StringUtils.isNotBlank(responseBody)) {
            JSONObject responseResult = JSON.parseObject(responseBody);
            Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
            Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
            if (code != 0 || subCode != 0) {
                throw new RuntimeException("调用终止算法调度任务执行接口返回异常,返回结果【" + responseBody + "】");
            }
        }
    }


    /**
     * 司小宝推送接口
     *  @param [title 标题 ,sub_title 子标题,url 跳转地址,phones 推送用户,cover 封面url]
     * @return true false
     * @throws Exception
     */
    public boolean appTaskPush(String... param) throws Exception {

        //请求path
        String path = "/v1/truck-driver-lite/gree/gree/task_push";

        if(param.length !=5) {
            throw new RuntimeException("参数异常");
        }

        JSONObject json = new JSONObject();
        json.put("title" , param[0]);
        json.put("sub_title" , param[1]);
        json.put("url" , param[2]);
        json.put("phones" , param[3]);
        json.put("cover" , param[4]);
        //Body内容
        String body = json.toJSONString();
        Request request = this.getPostRequest(path, body);
        Response response = customOpenApiClient.execute(request);
        System.out.println("*****:"+body);
        String responseBody = response.getBody();
        if(StringUtils.isNotBlank(responseBody)){
            JSONObject responseResult = JSON.parseObject(responseBody);
            System.out.println("responseResult"+responseResult);
            Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
            Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
            if(code == 0 && subCode == 0){
                return true;
            }else{
                throw new RuntimeException("调用app消息推送接口返回异常"+responseBody);
            }
        }

        return false;
    }
    /**
     * 司小宝查询对应司机信息接口
     * @param url
     * @param param
     * @return
     */
    public JSONObject appDriverInfo(String url, String token) throws IOException {

        url += "&ticket=".concat(token);

        HttpGet httpRequest = new HttpGet(url);
        CloseableHttpClient client = org.apache.http.impl.client.HttpClients.createDefault();

        RequestConfig config = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build(); // 握手超时、连接超时配置

        httpRequest.setConfig(config);

        HttpResponse httpResponse = client.execute(httpRequest);

        if(httpResponse.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("返回结果错误，返回 HTTP 代码位：" + httpResponse.getStatusLine().getStatusCode());
        }

        HttpEntity entity = httpResponse.getEntity();
        String strResult = EntityUtils.toString(entity);

        return JSON.parseObject(strResult) ;
    }

	public TaskPushDTO greeAppTaskPush(String... param) throws Exception {
		TaskPushDTO result = null;
		//请求path
        String path = "/v1/truck-driver-lite/gree/gree/task_push";
        if(param.length !=5) {
            throw new RuntimeException("参数异常");
        }

        JSONObject json = new JSONObject();
        json.put("title" , param[0]);
        json.put("sub_title" , param[1]);
        json.put("url" , param[2]);
        json.put("phones" , param[3]);
        json.put("cover" , param[4]);
        //Body内容
        String body = json.toJSONString();
        Request request = this.getPostRequest(path, body);
        Response response = customOpenApiClient.execute(request);
        System.out.println("*****:"+body);
        String responseBody = response.getBody();
        if(StringUtils.isNotBlank(responseBody)){
            JSONObject responseResult = JSON.parseObject(responseBody);
            System.out.println("responseResult"+responseResult);
            Integer code = responseResult.getInteger(OpenApiConstants.RESULT_CODE);
            Integer subCode = responseResult.getInteger(OpenApiConstants.RESULT_SUB_CODE);
            if(code == 0 && subCode == 0){
            	JSONObject data = responseResult.getJSONObject(OpenApiConstants.RESULT_DATA);
            	if (data != null && !data.isEmpty())
                    result = JSON.parseObject(data.toJSONString(), TaskPushDTO.class);
            }else{
                throw new RuntimeException("调用app消息推送接口返回异常"+responseBody);
            }
        }
		return result;
	}

}
